package com.ship.edge.outfile;

import cn.hutool.core.bean.BeanUtil;
import com.ship.edge.domain.CsvFileInfo;
import com.ship.edge.domain.KsbgCollectMsg;
import com.ship.edge.domain.KsbgCollectPoint;
import com.ship.edge.domain.KsbgCsvLine;
import com.ship.edge.utils.DirFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.alibaba.fastjson.JSON;

@Slf4j
@Component
public class OutputKsbgCsvFile {

    @Resource
    DirFileUtil dirFileUtil;

    private static final String[] KSBG_CSV_TITLE = {"nodeName","timestamp","pointNameEn","pointNameZh","pointValue","dateType"};
    private static final Lock writeLock = new ReentrantLock();

    public void mqttMsgToBean(String topic, String msg){
        List<KsbgCollectMsg> kcmList = new ArrayList<>();
        KsbgCollectMsg kcm = JSON.parseObject(msg, KsbgCollectMsg.class);
        writeKsbgDataToCSV(topic, kcm);
    }

    public void writeKsbgDataToCSV(String topic, KsbgCollectMsg kcm) {
        writeLock.lock();
        try{
            if(BeanUtil.isEmpty(kcm)){
                //如果没有数据则不处理
                return;
            }
            // 创建CSV文件
            CsvFileInfo cfi = createNewCSVFile(topic);
            // 使用try-with-resources确保资源关闭
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(cfi.getFilePath(), true));
                 CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withRecordSeparator("\n"))) {
                if (cfi.isNewFile()) {
                    //新文件先写入标题
                    csvPrinter.printRecord(KSBG_CSV_TITLE);
                }
                // 将数据写入CSV文件
                List<KsbgCsvLine> kclList = new ArrayList<KsbgCsvLine>();
                List<KsbgCollectPoint> kcpList = kcm.getData();
                for (int j = 0; j < kcpList.size(); j++) {
                    KsbgCsvLine line = new KsbgCsvLine();
                    KsbgCollectPoint kcp = kcpList.get(j);
                    line.setNodeName(kcm.getNodeName());
                    line.setTimestamp(kcm.getTimestamp());
                    line.setPointNameEn(kcp.getPointNameEn());
                    line.setPointNameZh(kcp.getPointNameZh());
                    line.setPointValue(kcp.getPointValue());
                    line.setDataType(kcp.getDataType());
                    csvPrinter.printRecord(line.toStringArray());
                }
            }
        }catch (IOException ex){
            ex.printStackTrace();
            log.error("写入csv失败：{}", ex.getMessage());
        }finally {
            writeLock.unlock();
        }


    }

    public CsvFileInfo createNewCSVFile(String topic) throws IOException {
        CsvFileInfo cfi = null;
        Calendar calendar = Calendar.getInstance();
        // 创建 SimpleDateFormat 对象，并指定日期格式
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHH");
        // 将日期对象格式化为字符串
        String formattedDate = sdf1.format(calendar.getTime());
        String fileName = topic + "-" + formattedDate + ".csv";
        String filePath = dirFileUtil.getFileDatePath(calendar, fileName, "yyyyMMdd", "yyyyMMddHH");
        File csvFile = new File(filePath);
        //不存在则创建
        if(!csvFile.exists()){
            FileUtils.touch(csvFile);
            cfi = new CsvFileInfo(true, filePath, fileName);
            log.info("创建csv文件，文件名：{}", filePath);
        }else{
            cfi = new CsvFileInfo(false, filePath, fileName);
            log.info("己有csv文件，文件名：{}", filePath);
        }
        return cfi;
    }


}
